package io;

import java.io.*;

/**
 * @author Cheng Jun
 * Description:
 * An InputStreamReader is a bridge from byte streams to character streams:
 * It reads bytes and decodes them into characters using a specified charset.
 * InputStreamReader 是字节流到字符流的桥梁。
 * @version 1.0
 * @date 2022/8/14 17:03
 * @see InputStreamReader 读源码注释
 * 同理 InputStreamWriter 也是一样的，以后再补上
 */
public class InputStreamReaderExample {

    public static void main(String[] args) throws IOException {
        // new InputStreamReader()
        read();
        readGBK();
    }

    // 演示读取GBK 文件的乱码问题。FileReader 默认读取的字符集是UTF-8
    private static void read() throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("src/io/TestFile/GBK文件.txt"));
        String strData = null;
        while ((strData = bufferedReader.readLine()) != null) {
            System.out.println(strData);
        }
        bufferedReader.close();
    }

    private static void readGBK() throws IOException {
        // 字节输入流
        FileInputStream fileInputStream = new FileInputStream("src/io/TestFile/GBK文件.txt");
        // 字节输入流转换成字符输入流 InputStreamReader
        InputStreamReader gbkReader = new InputStreamReader(fileInputStream, "gbk");
        // 字符输入流 转换成 缓冲式字符输入流
        BufferedReader bufferedReader = new BufferedReader(gbkReader);
        String strData = null;
        // 读取文件内容
        while ((strData = bufferedReader.readLine()) != null) {
            System.out.println(strData);
        }
        bufferedReader.close();
    }
}
